<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class JkblShanghuWithdraw extends Model
{
    public $timestamps = false;
    protected $table = "jkbl_shanghu_withdraw";

    const STATUS_WAITTING = 0;
    const STATUS_YES = 1;
    const STATUS_NO = 2;
    const STATUS_DONE = 3;

    static $StatusDisplay = [
        self::STATUS_WAITTING => '待审核',
        self::STATUS_YES => '通过',
        self::STATUS_NO => '不通过',
        self::STATUS_DONE => '已打款',
    ];


    ########关联关系

    public function shanghu()
    {
        return $this->belongsTo(ShopInfo::class, 'shid', 'id');
    }

    ########end


    /**
     * 提现通过
     * @param $jkblShanghuWithdraw
     * @return array|\Exception
     * @throws \Exception
     */
    static function WithdrawDone($jkblShanghuWithdraw)
    {
        DB::beginTransaction();

        //修改状态
        $jkblShanghuWithdraw->status = JkblShanghuWithdraw::STATUS_DONE;
        $jkblShanghuWithdraw->checktime = $jkblShanghuWithdraw->paytime = time();
        if (!$jkblShanghuWithdraw->save()) {
            DB::rollBack();

            return error('修改状态失败');
        }

        //发送推送消息
        $Jpush = JpushShMessage::SendJpush($jkblShanghuWithdraw->shid, JpushShMessage::TYPE_WITHDRAW_DONE,"您于".date('Y-d-m H:i',$jkblShanghuWithdraw->createtime)."的{$jkblShanghuWithdraw->money}元提现审核成功。请于支付宝查收。", JpushShMessage::RECEIVE_SH);
        if ($Jpush['status'] !== 1) {
            DB::rollBack();

            return $Jpush;
        }

        DB::commit();

        return success();
    }


    /**
     * 提现不通过
     * @param $jkblShanghuWithdraw
     * @return array|\Exception
     * @throws \Exception
     */
    static function WithdrawNo($jkblShanghuWithdraw, $request)
    {
        DB::beginTransaction();

        //修改状态
        $jkblShanghuWithdraw->status = JkblShanghuWithdraw::STATUS_NO;
        $jkblShanghuWithdraw->checktime  = time();
        $jkblShanghuWithdraw->refuse_content  = $request->refuse_content;
        if (!$jkblShanghuWithdraw->save()) {
            DB::rollBack();

            return error('修改状态失败');
        }

        //退还金额
        if (!DB::table('s_shanghu')->where('id', $jkblShanghuWithdraw->shid)->increment('wallet', $jkblShanghuWithdraw->money)) {
            DB::rollBack();

            return error('退还金额失败');
        }

        //发送推送消息
        $Jpush = JpushShMessage::SendJpush($jkblShanghuWithdraw->shid, JpushShMessage::TYPE_WITHDRAW_DONE, "您于".date('Y-d-m H:i',$jkblShanghuWithdraw->createtime)."的{$jkblShanghuWithdraw->money}元提现审核失败。原因{$request->refuse_content}。", JpushShMessage::RECEIVE_SH);
        if ($Jpush['status'] !== 1) {
            DB::rollBack();

            return $Jpush;
        }

        DB::commit();

        return success();
    }
}
